package com.luntan.school.web.servlet.admin;

import com.luntan.school.model.Admin;
import com.luntan.school.service.AdminService;
import com.luntan.school.service.impl.AdminServicelmpl;
import com.luntan.school.web.servlet.util.BaseServlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "AdminServlet", value = "/admin/admin")
public class AdminServlet extends BaseServlet {
   AdminService adminService = new AdminServicelmpl();

   public void list() throws ServletException,IOException {
       List<Admin> adminList = adminService.getAllAdmins();
       request.setAttribute("adminList",adminList);

       //跳转管理员列表页面
       request.getRequestDispatcher("").forward(request,response);
   }

   public void add()throws ServletException,IOException {
       //跳转管理员编辑页面
       request.getRequestDispatcher("").forward(request,response);

   }

   public void edit() throws ServletException,IOException {
       Integer id = Integer.parseInt(request.getParameter("id"));
       Admin admin = adminService.getAdminById(id);
       request.setAttribute("admin",admin);
       //跳转管理员编辑页面
       request.getRequestDispatcher("").forward(request,response);
   }

   public void save() throws IOException {
       String account =request.getParameter("account");
       String name =request.getParameter("name");
       String password =request.getParameter("password");

       Admin admin = new Admin();
       admin.setAccount(account);
       admin.setName(name);
       admin.setPassword(password);

       String id = request.getParameter("id");
       if(id != null) { // id不为空，更新管理员
           adminService.update(admin);
       } else { // 新增管理员
           adminService.add(admin);
       }

       response.sendRedirect(request.getContextPath() + "/admin/admin?method=list");

   }
    public void delete() throws IOException {
        Integer id = Integer.parseInt(request.getParameter("id"));

        adminService.delete(id);
        response.sendRedirect(request.getContextPath() + "/admin/admin?method=list");
    }
}
